const http = require('http')
const url = require('url')
function createApplication(){
    // app就是真正的请求监听函数
    let app = function(req, res){
        const {pathname} = url.parse(req.url, true)
        for(let i = 0; i<app.routes.length; i++){
            let route = app.routes[i]
            if((route.method == req.method.toLowerCase() || route.method == 'all') && route.path == pathname){
                return route.handler(req,res)
            }
        }
        res.end(`Cannot ${req.method} ${pathname}`)
    }
    app.listen = function(){
        let server = http.createServer(app)
        server.listen.apply(server, arguments)
    }
    // 定义路由规则
    app.routes = [] //保存路由规则
    http.METHODS.forEach(function(method){
        method = method.toLowerCase();
        app[method] = function(path, handler){
            app.routes.push({
                method,
                path,
                handler
            })
        }
        
    })

    app.all = function(path, handler){
        app.routes.push({
            method: 'all',
            path,
            handler
        })
    }

    // 添加中间件
    app.use = function(path, handler){
        if(typeof handler != 'function'){
            handler = path;
            path = '/'
        }
        app.routes.push({
            method: 'middle',
            path,
            handler
        })
    }
    // app.get = function(path, handler){
    //     app.routes.push({
    //         method: 'get',
    //         path,
    //         handler
    //     })
    // }
    return app;
}

module.exports = createApplication;


// get 请求 post添加 put修改 delete删除